package com.xiezc.util;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * MD5码的生成工具
 * Created by wb-xzc291800 on 2017/6/23.
 */
@Slf4j
public class Md5Util {

    private static MessageDigest messagedigest;

    private final static int MODULESIZE = 2048;

    private final static int fileSize = 10 * 1024 * 1024;

    private static int MD5LENGTH = 16;

    public static String getBase64Md5(InputStream is) {
        String x = null;
        try {
            x = new String(Base64.getEncoder().encode(getMd5(is)));
        } catch (Exception e) {
            throw new TBPanException(e);
        }
        return x.replaceAll("/", "-");
    }

    public static byte[] getMd5(InputStream is) throws IOException {
        byte[] b = new byte[MODULESIZE + MD5LENGTH];
        int len = 0;
        byte[] x = new byte[2048];
        while ((len = is.read(x)) != -1) {

            if (len == MODULESIZE) {
                System.arraycopy(getBaseMd5(b), 0, b, 0, MD5LENGTH);
            } else {
                return getBaseMd5(b);
            }

        }
        return new byte[16];
        //throw new TBPanException("空文件计算md5码");
    }


    private static byte[] getBaseMd5(byte[] bytes) {
        if (messagedigest == null) {
            try {
                messagedigest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                log.error(e.getMessage(), e);
                return null;
            }
        }
        return messagedigest.digest(bytes);
    }
}


